const validate = require("validate.js");
const demoDao = require("../dao/demoDao");
const { ValidationError } = require("../utils/errors");

exports.getDemos = async () => {
    const res = await demoDao.getDemos();
    return res.map((item)=>{
        return {
            ...item,
            description: JSON.parse(item.description)
        }
    });
}

exports.addDemo = async (info) => {
    info.description = JSON.stringify(info.description);
    const res = validate.validate(info, {
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        description: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        url: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        thumb: {
            type: "string"
        },
        github: {
            type: "string"
        },
        order: {
            presence: {
                allowEmpty: false
            },
            type: "integer"
        }
    });
    if (!res) {
        return await demoDao.addDemo(info);
    }else{
        throw new ValidationError("数据验证失败");
    }
}

exports.updateDemo = async (id, info) => {
    info.description = JSON.stringify(info.description);
    const res = await demoDao.updateDemo(id, info);
    res.description = JSON.parse(res.description);
    return res;
}

exports.deleteDemo = async (id) => {
    await demoDao.deleteDemo(id);
    return true;
}
